#!/bin/bash

#
# Variables
#

# The temporary directory where to extract stuff
export TMPDIR=$(mktemp -d)

# The temporary archive name (.tar.bz2, .tbz)
export TMPARCH="$TMPDIR/archive.tbz"

# The main directory of the archive, where to get files, taken from the current
# script name without extension
export TMPARCHDIR=$(basename "$0")
TMPARCHDIR="$TMPDIR/${TMPARCHDIR%.*}"

# Special marker of end of file
export SPECIAL='ARCHIVE BEGINS HERE'

#
# Functions
#

# The main function
function Main() {

  if [ "$1" == "--assemble" ] && [ -e "$2" ] ; then
    Assemble "$2"
  else
    Extract && Install
    Purge
  fi

}

# Assembles the given file into an output self-extractable BASH script
function Assemble() {
  local ARCH="$1"
  local OUT="${ARCH%.*}.sh"
  local OFFSET=$(Offset)

  dd if="$0" of="$OUT" bs=1 count=$OFFSET > /dev/null 2>&1
  cat "$ARCH" >> "$OUT"
  chmod +x "$OUT"
}

# Performs custom install actions (TODO). Returns 0 on success, 1 on failure
function Install() {

  local FONTDIR=/usr/share/fonts/truetype/milli

  echo -n '[....] Installing fonts'

  mkdir -p $FONTDIR 2> /dev/null && \
    cp ${TMPARCHDIR}/*.ttf ${FONTDIR}/ 2> /dev/null && \
    fc-cache -f -v > /dev/null 2>&1

  if [ $? == 0 ]; then
    echo -e "\r[ \033[1;32mOK\033[m ]"
    return 0
  else
    echo -e "\r[\033[1;31mFAIL\033[m]"
    return 1
  fi

}

# Removes temporary garbage
function Purge() {
  echo -n '[....] Removing temporary files'
  rm -rf "$TMPDIR"
  echo -e "\r[ \033[1;32mOK\033[m ]"
}

# Finds the offset where to write the archive
function Offset() {
  local OFFSET
  local LEN=${#SPECIAL}
  let LEN=LEN+8

  OFFSET=$(grep -abo "### $SPECIAL ###" "$0" | head -n1 | cut -d: -f1)
  let OFFSET+=LEN

  echo $OFFSET

  #echo "--- BOF ---"
  #dd if="$0" of="/dev/stdout" bs=1 count=$OFFSET 2> /dev/null
  #echo "--- EOF ---"
}

# Extracts the archive into the temporary directory. Returns 0 on success,
# nonzero on failure
function Extract() {
  local OFFSET=$(Offset)

  echo -n '[....] Extracting the archive'

  dd if="$0" of="$TMPARCH" bs=1 skip=$OFFSET > /dev/null 2>&1 &&
    cd "$TMPDIR" 2> /dev/null && \
    tar xjf "$TMPARCH" 2> /dev/null

  if [ $? == 0 ]; then
    echo -e "\r[ \033[1;32mOK\033[m ]"
    return 0
  else
    echo -e "\r[\033[1;31mFAIL\033[m]"
    return 1
  fi
}

#
# Entry point
#

Main "$@"
exit $?

### ARCHIVE BEGINS HERE ###
